#include "../source/server.hpp"
// // bug，在更改完事件之后没有更新事件，导致无法进行监控
// // 当客户端关闭时，服务器端发生段错误，原因是我们在处理其他事件回调时，channel已经被关闭
// void HandleClose(Channel *channel)
// {
//     std::cout << "描述符" << channel->Fd() << "被关闭\n";
//     channel->Remove();
//     // channel->Poll()->AppendDeletedChannel(channel);
//     delete channel;
// }

std::unordered_map<uint64_t,ConnectionPtr> conns;
uint64_t next_conn_id = 1;
EventLoop loop;
LoopThreadPool *pool=nullptr;
int thr_num = 0;
void onMessage(const ConnectionPtr &conn,Buffer *buffer)
{
    size_t readable = buffer->ReadAbleSize();
    if (readable > 0) {
        std::string msg = buffer->ReadStringAndPop(readable);
        DLOG("收到数据: %s", msg.c_str());
        std::string reply = "你好: " + msg;
        conn->Send(reply.c_str(), reply.size());
        //conn->ShutDown();
        //DLOG("发送成功");
    }
}
void onClose(const ConnectionPtr &conn)
{
    conns.erase(conn->Id());
}
void onConnect(const ConnectionPtr &conn)
{
    DLOG("NEW CONNECTION:%p", conn.get());
}
void Accept(int fd)
{
    uint64_t conn_id = next_conn_id++;
    int num = (thr_num+1)%2;
    ConnectionPtr conn(new Connection(pool->NextLoop(),conn_id,fd));
    //DLOG("%d\n",fd);
    conn->SetSrvCloseCallBack(std::bind(onClose,std::placeholders::_1));
    conn->SetConnectCallBack(std::bind(onConnect,std::placeholders::_1));
    conn->SetMessageCallBack(std::bind(onMessage,std::placeholders::_1,std::placeholders::_2));
    //启动非活跃销毁
    conn->EnableInactiveRelase(10);
    conn->Established();
    conns.insert(std::make_pair(conn_id,conn));
    DLOG("New--------");
}

int main()
{
    pool=new LoopThreadPool(&loop);
    pool->SetThreadCount(2);
    pool->Create();
    Acceptor acceptor(&loop,8500);
    acceptor.SetAcceptCallBack(std::bind(Accept,std::placeholders::_1));
    acceptor.Listen();
    loop.Start();
    return 0;
}